package com.damage.materiel_dept.oa.completeOrder;

import com.damage.common.config.DepartmentConfig;
import com.damage.common.config.ProcessDefinitionConfig;
import com.damage.common.config.PurchaseInvoiceConfig;
import com.damage.common.config.PurchaseInvoiceDetailConfig;
import com.damage.common.entity.PurchaseInvoice;
import com.damage.common.entity.PurchaseInvoiceDetail;
import com.damage.common.exception.IdentityException;
import com.damage.common.exception.IncorrectPriceException;
import com.damage.common.exception.IncorrectStateException;
import com.damage.common.oa.completeOrder.CompleteOrderConfig;
import com.damage.materiel_dept.service.IPurchaseInvoiceService;
import com.google.common.base.Strings;
import com.sun.istack.internal.Nullable;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class StartCompleteOrderService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private IPurchaseInvoiceService purchaseInvoiceService;

    @Transactional
    public PurchaseInvoice startCompleteOrder(PurchaseInvoice purchaseInvoice)
            throws IncorrectStateException, IncorrectPriceException {
        //验证身份
        User user = identityService.createUserQuery().userFirstName(purchaseInvoice.getInspector()).singleResult();
        Group group = identityService.createGroupQuery().groupMember(user.getId()).singleResult();
        String groupId = group.getId();
        if (!DepartmentConfig.materielDept.equals(groupId)) {
            throw new IdentityException("用户的身份不是物料部的员工，不能启动流程！");
        }
        identityService.setAuthenticatedUserId(user.getId());

        //保存购货发票
        String businessKey = null;
        try {
            businessKey = purchaseInvoiceService.newPurchaseInvoice(purchaseInvoice).toString();
        } catch (IncorrectStateException e) {
            throw e;
        } catch (IncorrectPriceException e) {
            throw e;
        }

        ProcessInstance processInstance = null;
        try {

            //设置变量：购货发票是否和订单一致
            PurchaseInvoice newPurchaseInvoice = purchaseInvoiceService.findById(Integer.parseInt(businessKey));
            Map<String, Object> vars = new HashMap<>();
            if (newPurchaseInvoice.getIsConsistent() == PurchaseInvoiceConfig.CONSISTENT){
                vars.put(CompleteOrderConfig.CONSISTENT,true);
            }else{
                vars.put(CompleteOrderConfig.CONSISTENT,false);
            }
            //启动流程
            processInstance = runtimeService.startProcessInstanceByKey(ProcessDefinitionConfig.COMPLETE_ORDER, businessKey,vars);
            String processInstanceId = processInstance.getId();
            //设置购货发票相应的流程实例id
            purchaseInvoiceService.setProcessInstanceId(purchaseInvoice.getId(), processInstanceId);
            log.info("start process of {key={}, bkey={}, pid={}}", new Object[]{"completeOrder", businessKey, processInstanceId});
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        PurchaseInvoice result = purchaseInvoiceService.findById(purchaseInvoice.getId());

        return result;
    }
}
